﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetStar.TheKing.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace DotNetStar.TheKing.Web.Pages.Account
{
    using DotNetStar.TheKing.Infrastructure;
    using DotNetStar.TheKing.Web.Models;
    using Filters;
    using System.ComponentModel.DataAnnotations;
    
    public class RegisterModel : PageModel
    {
        private readonly UserService _userService;
        private readonly VerifyCodeService _verifyCodeService;


        public RegisterModel(UserService userService,
            VerifyCodeService verifyCodeService)
        {
            _userService = userService;
            this._verifyCodeService = verifyCodeService;
        }
        

        public string ReturnUrl => "/User/Setting/Information";


        public IActionResult OnGet()
        {
            if (User.Identity.IsAuthenticated)
            {
                return Redirect(this.ReturnUrl);
            }
            return Page();
        }

        public async Task<IActionResult> OnPostAsync(string userName,string mobile,string code)
        {
            if (userName.IsNullOrWhiteSpace())
            {
                return StatusCode(400, "昵称不能为空");
            }
            if(userName.Length<2 || userName.Length > 15)
            {
                return StatusCode(400, "昵称的长度必须是2-15个字符");
            }
            if (mobile.IsNullOrWhiteSpace())
            {
                return StatusCode(400, "手机号不能为空");
            }

            if (code.IsNullOrWhiteSpace())
            {
                return StatusCode(400, "验证码不能为空");
            }

            var validateResult = _verifyCodeService.VerifyCode(mobile, code);
            if (!validateResult)
            {
                return StatusCode(400, "验证码不正确");
            }

            var hasUserName = (await _userService.GetUserAsync(userName, AccountTypes.UserName)) == null;
            if (!hasUserName)
            {
                return StatusCode(400, "昵称已经存在，请更换");
            }
            var hasMobile = (await _userService.GetUserAsync(mobile, AccountTypes.Mobile)) == null;
            if (!hasMobile)
            {
                return StatusCode(400, "手机号已经存在，请更换");
            }

            try
            {
                var user = await _userService.CreateUserAsync(mobile, userName);

                //认证
                await HttpContext.SignInAsync(user);

                return StatusCode(200,this.ReturnUrl);
            }catch(Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }
    }
}